import axios from 'axios'
import { Message } from 'element-ui'
// import router from '@/router'
// import { toLoginPage } from "@/utils/index";

// 创建 axios 实例
const service = axios.create({
  // baseURL (.env.development)
  baseURL: './',
  // 请求头设置
  headers: { 'Content-Type': 'application/json' },
  // 跨域请求时发送cookies
  withCredentials: true,
  // 请求超时
  timeout: 50000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // config.headers['authorization'] = $storage.getStorage('token') || ''
    return config
  },
  error => {
    // 做一些请求错误的事情
    return Promise.reject(error)
  }
)
async function readBlob(data) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsText(data, 'utf8');
    reader.onload = function () {
      return resolve(JSON.parse(this.result))
    }
  })
}
// 响应拦截器
service.interceptors.response.use(
  async response => {
    let res = response.data
    if (response.config.responseType === "blob") {
      if (response.data.type === 'application/json') {
        res = await readBlob(response.data)
      } else {
        return response.data;
      }
    }
    // const res = response.data
    // 如果自定义代码不是0000，则判断为错误。
    if (res.code === '0000') {
      // console.log(JSON.stringify(res.data))
      return res.data
    }
  },
  error => {
    // console.log('响应拦截器err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.message || error)
  }
)

export default service
